﻿using FlashPay.Service.Interface.Receipt;
using System;
using System.Collections.Generic;
using System.Text;

using FlashPay.DAO.Interface;
using FlashPay.EF;
using FlashPay.EF.Models;
using FlashPay.Entity;
using FlashPay.DAO.Interface.Receipt;
using FlashPay.Service.Shared;
using FlashPay.Entity.Parameter;
using FlashPay.Entity.Response.Payment;
using FlashPay.Entity.Response.Company;
using FlashPay.Util;
using System.Linq;
using FlashPay.Entity.Request.Receipt;
using FlashPay.Entity.Enum;
using Microsoft.AspNetCore.Http;

namespace FlashPay.Service.Impl.Receive
{
   public class ReceiptServiceImpl : BaseService,ReceiptService
    {
        /// <summary>
        /// 用户数据接口
        /// </summary>
        private readonly ReceiptDao _receive;

        /// <summary>
        /// 日志权限数据接口
        /// </summary>
        private readonly LogDao _logDao;

        /// <summary>
        /// 日志模型
        /// </summary>
        private readonly LogRecord _logRecord;

        /// <summary>
        /// 公司数据接口
        /// </summary>
        private readonly CompanyDao _companyDao;

        /// <summary>
        /// 银行数据接口
        /// </summary>
        private readonly BankDao _bankDao;

        /// <summary>
        /// 
        /// </summary>
        public readonly IHttpContextAccessor _accessor;

        /// <summary>
        /// 上下文
        /// </summary>
        private FlashPayContext _context { set; get; }

        /// <summary>
        /// 注入
        /// </summary>
        /// <param name="userInfo">用户数据接口</param>
        public ReceiptServiceImpl(ReceiptDao receive, LogDao logDao, LogRecord logRecord, CompanyDao companyDao, BankDao bankDao, IHttpContextAccessor accessor, FlashPayContext context)
        {
            this._receive = receive;
            this._logDao = logDao;
            this._logRecord = logRecord;
            _companyDao = companyDao;
            _bankDao = bankDao;
            this._accessor = accessor;
            this._context = context;
        }

        /// <summary>
        /// 获取收款卡管理
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public DataGrid<PaymentCardResponse> GetReceiptCard(PaymentCardQuery query)
        {
            query.CompanyIds = _bankDao.GetCompanyIDList(query.CompanyId.Value);
            query.CompanyId = null;
            return _receive.GetReceiptCard(query);
        }

        //获取付款记录列表
        public PagedList<DepositOrPaymentRecordResponse> GetReceiptRecordList(PaymentRecordQuery query)
        {
            PagedList<DepositOrPaymentRecordResponse> response = new PagedList<DepositOrPaymentRecordResponse>()
            {
                Success = false
            };

            if (query.StartTime == null || query.EndTime==null)
            {
                response.ErrorMessage = "时间参数错误";
                return response;
            }

            #region 公司条件过滤
            query.CompanyIds = _bankDao.GetCompanyIDList(query.CompanyId.Value);
            query.CompanyId = null;
            if (query.CompanyIds == null)
            {
                response.ErrorMessage = "公司参数错误";
                return response;
            }
            #endregion
            return _receive.GetReceiptRecordList(query);
        }

        /// <summary>
        /// 存款记录查询
        /// </summary>
        /// <param name="query">查询条件</param>
        public DataGrid<DepositRecordResponse> GetReceiptRecord(DepositRecordQuery query)
        {
            #region 公司条件过滤
            query.CompanyIds = _bankDao.GetCompanyIDList(query.CompanyId.Value);
            query.CompanyId = null;
            if (query.CompanyIds == null)
            {
                throw new Exception("公司参数错误");
            }
            #endregion

            return _receive.GetReceiptRecord(query);
        }

        /// <summary>
        /// 重置订单
        /// </summary>
        /// <param name="orderNo">订单编号</param>
        /// <returns></returns>
        public JResult ResetNoticeStatus(long orderNo)
        {
            var result = new JResult()
            {
                Success = false
            };

            try
            {
                if (orderNo <= 0)
                {
                    throw new Exception("未获取到参数");
                }

                var resetStatus = _receive.ResetNoticeStatus(orderNo);
                if (resetStatus){
                    result.Success = true;
                    result.SuccessMessage = "操作成功";
                }
                else
                {
                    throw new Exception("操作失败");
                }
            }
            catch (Exception ex) {
                result.ErrorMessage = ex.Message;
            }

            return result;
        }

        /// <summary>
        /// 收款匹配记录（补推送）
        /// </summary>
        /// <param name="orderNo">订单编号</param>
        /// <returns></returns>
        public JResult ReceiptMatchMakeUp(ReceiptMatchMakeUpRequest request)
        {
            var result = new JResult()
            {
                Success = false
            };

            try
            {
                if (request.OrderNo <= 0 || request.Id<=0)
                {
                    throw new Exception("未获取到参数");
                }


                var resetStatus = _receive.ReceiptMatchMakeUp(request.OrderNo);
                if (resetStatus>0)
                {
                    //日志
                    _logRecord.Ip = _accessor.HttpContext.GetUserIp();
                    _logRecord.LogType = LogRecordLogType.DepositMatchRecord_MakeUp.GetHashCode();
                    _logRecord.LogLevel = (sbyte)LogLevel.Success.GetHashCode();
                    _logRecord.CreateDate = DateTime.Now;
                    _logRecord.LogRemark = $"收款匹配记录【手动】补推送成功,收款匹配订单号:{request.Id},收款记录订单号:{request.OrderNo}";
                    _logDao.Insert(_logRecord);

                    result.Success = true;
                    result.SuccessMessage = "补推送收款订单成功！";
                }
                else
                {
                    //日志
                    _logRecord.Ip = _accessor.HttpContext.GetUserIp();
                    _logRecord.LogType = LogRecordLogType.DepositMatchRecord_MakeUp.GetHashCode();
                    _logRecord.LogLevel = (sbyte)LogLevel.Failure.GetHashCode();
                    _logRecord.CreateDate = DateTime.Now;
                    _logRecord.LogRemark = $"收款匹配记录【手动】补推送失败,收款匹配订单号:{request.Id},收款记录订单号:{request.OrderNo}";
                    _logDao.Insert(_logRecord);

                    result.SuccessMessage = "补推送收款订单失败！";
                }
            }
            catch (Exception ex)
            {
                result.ErrorMessage = ex.Message;
            }

            return result;
        }

        /// <summary>
        /// 根据编号获取公司
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns>Company</returns>
        private List<CompanyResponse> GetCompany(int companyId, int level)
        {
            var companyRequest = new EF.Models.Company()
            {
                CompanyId = companyId,
                CompanyPid = -1,
                CompanyStatus = 1
            };

            var companyList = new BaseModel<List<EF.Models.Company>>();

            _companyDao.Get(companyList, companyRequest, level);
            var companyResponse = new List<CompanyResponse>();
            if (companyList.Success)
            {
                foreach (var item in companyList.Result)
                {
                    companyResponse.Add(new CompanyResponse()
                    {
                        CompanyID = item.CompanyId,
                        CompanyName = item.CompanyName,
                        CompanyStatus = item.CompanyStatus
                    });
                }
            }
            return companyResponse;
        }

        /// <summary>
        /// 收款记录[重置]
        /// </summary>
        /// <param name="request"></param>
        public JResult MakeUp(MakeUpRequest request)
        {
            var result = _receive.MakeUp(request);
            if (result.Success)
            {
                //日志
                _logRecord.Ip = _accessor.HttpContext.GetUserIp();
                _logRecord.LogType = LogRecordLogType.DepositRecord_MakeUp.GetHashCode();
                _logRecord.LogLevel = (sbyte)LogLevel.Success.GetHashCode();
                _logRecord.CreateDate = DateTime.Now;
                _logRecord.LogRemark = $"收款记录重置成功,订单号:{request.OrderNo}";
                _logDao.Insert(_logRecord);

                result.Success = true;
                result.SuccessMessage = "收款记录重置订单成功！";
            }
            else
            {
                //日志
                _logRecord.Ip = _accessor.HttpContext.GetUserIp();
                _logRecord.LogType = LogRecordLogType.DepositRecord_MakeUp.GetHashCode();
                _logRecord.LogLevel = (sbyte)LogLevel.Failure.GetHashCode();
                _logRecord.CreateDate = DateTime.Now;
                _logRecord.LogRemark = $"收款记录重置失败,订单号:{request.OrderNo}";
                _logDao.Insert(_logRecord);

                result.SuccessMessage = "收款记录重置订单失败！";
            }
            return result;
        }

        /// <summary>
        /// 改变公司
        /// </summary>
        /// <param name="request"></param>
        public JResult ChangeCompany(ChangeCompanyRequest request)
        {
            var companyIds = _bankDao.GetCompanyIDList(request.LoginCompanyId);

            if (!companyIds.Contains(request.CompanyId))
            {
                return new JResult()
                {
                    Success = false,
                    ErrorMessage = "无效公司编号"
                };
            }
            var result = _receive.ChangeCompany(request);

            return result;
        }
    }
}
